package com.zqweb.gulimall.ssoclient1.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {
    @Value("${sso.server.url}")
    private String ssoServerUrl;// http://ssoserver.com:8080


    // 访问无需登录即可浏览的资源
    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        return "Hello！";
    }

    // 访问需要登录才可浏览的资源
    @GetMapping("/getEmployees")
    public String getEmployees(Model model, HttpSession session,
                               @RequestParam(value = "token",required = false) String token){
        // token：用于表示sso-server单点登陆是否处理完毕、登陆成功
        if(!StringUtils.isEmpty(token)){
            // 利用RestTemplate远程的Restful接口调用模板，来获取指定token对应Redis中存储记录的值
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://ssoserver.com:8080/getSessionUserInfo?token=" + token, String.class);
            String body = responseEntity.getBody();
            session.setAttribute("loginUser",body);
        }
        Object sessionUser = session.getAttribute("loginUser");
        if(sessionUser == null){
            // 跳转到sso-server作统一登录，注意：跳转时携带该处理器方法映射的接口，以便于登录以后重新返回来
            return "redirect:" + ssoServerUrl + "/login?redirect_url=http://client1.com:8081/getEmployees";
        }else{
            List<String> list = new ArrayList<>();
            list.add("张三");
            list.add("李四");
            list.add("王五");
            model.addAttribute("employees",list);
            return "List";
        }

    }

}
